package org.example.intercerpt;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.example.config.CacheUtil;
import org.example.config.LocalUerContext;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Objects;
import java.util.Optional;

@Slf4j
public class CookieInterceptor implements HandlerInterceptor {


    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("request {} coming", request.getRequestURI());
        if (Objects.isNull(request.getCookies())) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // 401状态码
            return false;
        }
        Optional<Cookie> optionalCookie = Arrays.stream(request.getCookies())
                .filter(x -> "login_token".equalsIgnoreCase(x.getName()))
                .findFirst();
        if (optionalCookie.isEmpty()) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // 401状态码
            return false;
        }
        Cookie cookie = optionalCookie.get();
        if (StringUtils.isEmpty(CacheUtil.getCache().asMap().get(cookie.getValue()))) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // 401状态码
            return false;
        }
        LocalUerContext.setLocalUserId(CacheUtil.getCache().asMap().get(optionalCookie.get().getValue()));
        return true;
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        LocalUerContext.clear();
    }
}
